<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <title>OAuth2.0 授权码模式演示</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
  <h2>OAuth2.0 授权码模式对接演示</h2>
  <div id="form-area">
    <label>SSO授权地址(authorization_endpoint): <input id="ssoUrl" style="width:400px" value="http://172.16.127.100:37787/connect/authorize"></label><br>
    <label>client_id: <input id="clientId" value="bs"></label><br>
    <label>client_secret: <input id="clientSecret" value="secret"></label><br>
    <label>redirect_uri: <input id="redirectUri" style="width:400px" value="http://127.0.0.1:5500/index.html"></label><br>
    <label>scope: <input id="scope" value="openid profile roles"></label><br>
    <label>token_endpoint: <input id="tokenEndpoint" style="width:400px" value="http://172.16.127.100:37787/connect/token"></label><br>
    <label>userinfo_endpoint: <input id="userinfoEndpoint" style="width:400px" value="http://172.16.127.100:37787/connect/userinfo"></label><br>
    <button id="startAuth">开始授权</button>
  </div>
  <div id="result"></div>

  <script>
    // 自动填充redirect_uri为当前页面
    $('#redirectUri').val(window.location.origin + window.location.pathname);

    // 优先从localStorage读取参数填充input
    $('#form-area input').each(function() {
      const v = localStorage.getItem(this.id);
      if (v) $(this).val(v);
    });
    // input变更时保存到localStorage
    $('#form-area input').on('input', function() {
      localStorage.setItem(this.id, $(this).val());
    });

    // 检查URL是否有code参数
    function getQueryParam(name) {
      const url = window.location.search;
      const reg = new RegExp('[?&]' + name + '=([^&#]*)', 'i');
      const r = url.match(reg);
      if (r != null) return decodeURIComponent(r[1]);
      return null;
    }

    // 步骤1：点击开始授权
    $('#startAuth').click(function () {
      const ssoUrl = $('#ssoUrl').val();
      const clientId = $('#clientId').val();
      const redirectUri = $('#redirectUri').val();
      const scope = $('#scope').val();
      const state = Math.random().toString(36).substr(2, 8);

      const authUrl = `${ssoUrl}?client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${encodeURIComponent(scope)}&state=${state}`;
      window.location.href = authUrl;
    });

    // 步骤2：如果有code，自动换token
    $(function () {
      const code = getQueryParam('code');
      if (code) {
        $('#form-area').hide();
        $('#result').html('<b>检测到code，正在换取token...</b>');
        const tokenEndpoint = $('#tokenEndpoint').val() || prompt('请输入token_endpoint:');
        const clientId = $('#clientId').val() || prompt('请输入client_id:');
        const clientSecret = $('#clientSecret').val() || prompt('请输入client_secret:');
        const redirectUri = $('#redirectUri').val() || window.location.origin + window.location.pathname;

        // 步骤3：用code换token
        $.ajax({
          url: tokenEndpoint,
          type: 'POST',
          data: {
            grant_type: 'authorization_code',
            code: code,
            redirect_uri: redirectUri,
            client_id: clientId,
            client_secret: clientSecret
          },
          success: function (tokenRes) {
            $('#result').html('<b>Token获取成功：</b><pre>' + JSON.stringify(tokenRes, null, 2) + '</pre>');
            // 步骤4：用access_token获取用户信息
            if (tokenRes.access_token) {
              const userinfoEndpoint = $('#userinfoEndpoint').val() || prompt('请输入userinfo_endpoint:');
              $.ajax({
                url: userinfoEndpoint,
                type: 'GET',
                headers: {
                  'Authorization': 'Bearer ' + tokenRes.access_token
                },
                success: function (userinfo) {
                  $('#result').append('<b>用户信息：</b><pre>' + JSON.stringify(userinfo, null, 2) + '</pre>');
                },
                error: function (xhr) {
                  $('#result').append('<b>获取用户信息失败：</b><pre>' + xhr.responseText + '</pre>');
                }
              });
            }
          },
          error: function (xhr) {
            $('#result').html('<b>Token获取失败：</b><pre>' + xhr.responseText + '</pre>');
          }
        });
      }
    });
  </script>
</body>

</html>